#coding:utf-8
__author__ = 'huolu'

import MySQLdb
import sys


reload(sys)
sys.setdefaultencoding('utf8')

class HLMySQLdb:
    def __init__(self,host='',port=0,db='',user='',pwd=''):
        self.__host = host
        self.__port = port
        self.__db = db
        self.__user = user
        self.__pwd = pwd
        self.conn = None
        self.cursor= None

    def getHost(self):
        return self.__host
    def setHost(self,host):
        self.__host = host

    def getPort(self):
        return self.__port
    def setPort(self,port):
        self.__port = port

    def getDb(self):
        return self.__db
    def setDb(self,db):
        self.__db = db

    def getUser(self):
        return self.__user
    def setUser(self,user):
        self.__user = user

    def getPwd(self):
        return  self.__pwd
    def setPwd(self,pwd):
        self.__pwd = pwd

    def getPwd(self):
        return self.__pwd
    def connect(self):
        try:
            self.conn = MySQLdb.connect(host=self.__host,port=self.__port,db=self.__db,user=self.__user,passwd=self.__pwd,charset='utf8')
            self.cursor = self.conn.cursor()
        except:
            print u'数据库连接失败'
        else:
            print u'连接数据库成功'

    #这个方法主要用于查询数据，query表示查询语句，args是元祖类型的查询参数，如果query中没有查询参数则这个参数可以不传
    def getData(self,query,args=None):
        self.execute(query,args)
        return  self.cursor.fetchall()

    #这个方法主要针对增、删、改，并且方法影响的行数，如果SQL在执行过程中报错则回滚
    def execute(self,query,args=None):
        try:
            self.cursor.execute(query,args)
        except:
            self.conn.rollback()
            print u'SQL执行出错：\n' +\
                  u'SQL:'+query+'\n' +\
                  u'args:'+str(args)

    def close(self):
        try:
            self.conn.close()
        except:
            print u'关闭数据库失败！'

    def isConnect(self):
        if not self.conn :
            print u'还未连接数据库,文件->新建连接'
            return False
        return True


